using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Common.Core.Configuration
{
	class SettingsView : ConfigurationView<Settings>
	{
		public SettingsView()
		{}

		public SettingsView( IConfigurationSource source ) : base( source )
		{}

		public Type ResolveConfigurationType( Type baseConfigurationType, Type target )
		{
			// First check configuration:
			if ( Settings != null )
			{
				foreach ( ConfigurationTargetSettings mapping in Settings.ConfigurationTargetMappings )
				{
					if ( mapping.Type == target )
					{
						return mapping.TargetConfigurationType;
					}
				}
			}

			// Now check metadata:
			Type result = Cache.ContainsKey( target ) ? Cache[target] : null;
			return result;
		}

		static Dictionary<Type, Type> Cache
		{
			get { return cache ?? ( cache = ResolveCache() ); }
		}	static Dictionary<Type, Type> cache;

		static Dictionary<Type, Type> ResolveCache()
		{
			Dictionary<Type, Type> result = new Dictionary<Type, Type>();
			foreach ( Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() )
			{
				foreach ( ConfigurationTargetMappingAttribute attribute in assembly.GetCustomAttributes( typeof(ConfigurationTargetMappingAttribute), true ) )
				{
					result.Add( attribute.TargetType, attribute.ConfigurationType );
				}
			}
			return result;
		}

	}
}